|
|
|
|
|
|
|
Figure 8.2
The Option Explicit statement
is added to your program. |
|
|
|
|
|
|
|
|
If a form or module contains the Option Explicit statement and you fail to declare a variable, you receive the error message Variable not defined when you try to run your code. The integrated debugger highlights the offending variable and aborts the compilation of your program. The benefit of this message is that it helps you avoid errors in your code that might be caused by typographical errors. For example, you might declare a variable using the following statement: |
|
|
|
|
|
|
|
|
If, in a later statement, you mistype the variable name, Visual Basic catches the error for you rather than continues with unpredictable results. For example, the following statement causes an error if Option Explicit is used; otherwise, the program continues without having set the value of the intended variable: |
|
|
|
|
|
|
|
|
Without the Option Explicit statement, the previous line of code would create an additional variable. In other words, you would have two string variables: sMyName and sMyNme. |
|
|
|
|
CAUTION
|
|
|
|
|
If you set the Require Variable Declaration option after starting to create a program, the option has no effect on any forms or modules that have already been created. In this case, you can add the Option Explicit statement as the first line of code in the General Declarations section of any existing forms or modules. |
|
|
|
|
|
|
| |
|
|
|
|
If you use some capital letters in your variable declarations, enter your code in all lowercase letters. Visual Basic automatically sets the capitalization of your variables to match the declarations. This convention gives you an immediate visual indication that you typed the name correctly. |
|
|
|
|
|
|
|